package com.next

import grails.converters.JSON
import grails.gorm.transactions.Transactional
import grails.validation.ValidationException
import org.springframework.security.access.annotation.Secured

import java.text.DecimalFormat
import java.text.SimpleDateFormat

import static org.springframework.http.HttpStatus.*

@Secured(['isAuthenticated()'])
class RiskWarningController
{
    def apiService
    def springSecurityService
    def scoreApiService
    def dataSource
    def componentService
    def riskWarningService
    def developerApiService

    static allowedMethods = [save: "POST", update: "PUT", delete: "DELETE"]

    @Transactional
    def update(RiskWarning riskWarning)
    {
        if (riskWarning == null)
        {
            transactionStatus.setRollbackOnly()
            notFound()
            return
        }

        if (riskWarning.hasErrors())
        {
            transactionStatus.setRollbackOnly()
            respond riskWarning.errors, view: 'edit'
            return
        }

        riskWarning.save flush: true

        request.withFormat {
            form multipartForm {
                flash.message = message(code: 'default.updated.message', args: [message(code: 'riskWarning.label', default: 'RiskWarning'), riskWarning.id])
                redirect url: params['targetUri']
            }
            '*' { respond riskWarning, [status: OK] }
        }
    }

    def updateRiskWarning()
    {

    }

    /**
     * 押品价值波动列表*/
    def priceFluctuationsRatioWarning(Integer max)
    {
        params.max = Math.min(max ?: 10, 100)
        params.offset = params.offset ? params.offset.toInteger() : 0
        def city = params['city']
        def district = params['district']
        def residentialType = params['residentialType']
        def communityId = params['communityId']
        def user = User.findById(springSecurityService.principal.id)
        //        def sql = "from RiskWarning r where r.type.code = '1' and r.isWarning = '1' and r.bankAccount.id in " + Account.FilterAccountSql(user)
        //        if (city && city != '-1')
        //        {
        //            sql += " and r.collateral.city.zoneNumber = '${city}' "
        //        }
        //        if (district && district != '-1')
        //        {
        //            sql += " and r.collateral.district.zoneNumber = '${district}' "
        //        }
        //        if(residentialType){
        //            sql += " and r.collateral.estate.buildingType.id = ${residentialType} "
        //        }
        //        if(communityId){
        //            sql += " and r.collateral.estate.communityId = ${communityId} "
        //        }
        //        def sql1 = " select count(*) " + sql
        //        sql += " order by r.modifiedDate desc "
        //
        //        def riskWarningList = RiskWarning.executeQuery(sql, [max: params.max, offset: params.offset]).asList()
        //        def riskWarningcount = RiskWarning.executeQuery(sql1)
        //        def districtList = District.findAllByParentAreaAndAreaLevel(City.findByZoneNumberAndAreaLevel(city, 2), 3)
        respond null, model: [riskWarningList: null, riskWarningcount: 0, districtList: null, params: params]

    }

    /**
     * 押品价值波动详情*/
    def priceFluctuationsRatioWarningShow(House collateral)
    {
        def estate = null
        //        if(!collateral){
        //            estate = Estate.findById(Long.parseLong(params["id"]))
        //            collateral = Collateral.findByEstate(estate)
        //            params.status = RiskWarning.findByCollateral(collateral)?.status?.name
        //        }else{
        //            estate = collateral?.estate
        //        }
        //        println "params:   "+params
        //
        //        def zoneNumber = estate?.city?.zoneNumber
        //        def communityId = estate.communityId
        //        //小区详情
        //        def community = apiService.community(zoneNumber, communityId)
        //        //小区照片
        //        def communityPicArr = apiService.picture(zoneNumber, communityId, 5, 3)
        //        //成交案例列表
        //        def saleList = apiService.sale(zoneNumber, communityId)
        //        //挂牌案例列表
        //        def listings = apiService.listing(zoneNumber, communityId)
        //        // 贷款信息
        //        def mortgageList = MortgageCollateral.findAllByCollateral(collateral)*.mortgage
        //
        //        def replaceCollateral = collateral?.replacementCollateral

        respond collateral, model: [params: params, mortgageList: null, estateDetail: estate, community: null, replaceCollateral: null, communityPicArr: null, saleList: null, listings: null]

    }

    /**
     * 押品价值波动处置*/
    //    def disposalPriceFluctuations(Estate estate)
    //    {
    //        def status = ""
    //        try
    //        {
    //            estate.dealType = DataDict.findByCode("PriceFluctuations")
    //            estate.warningStatus = RiskWarningStatusDict.findByCode('3')
    //            estate.save flush: true
    //            status = "success"
    //        }
    //        catch (Exception e)
    //        {
    //            status = "false"
    //            e.printStackTrace()
    //        }
    //        render([status: status] as JSON)
    //    }

    /**
     * 押品价值波动删除*/
    //    def deletePriceFluctuations(Estate estate)
    //    {
    //        def status = ""
    //        try
    //        {
    //            estate.warningStatus = null
    //            estate.priceFluctuationsRatio = null
    //            estate.dealType = null
    //            estate.save flush: true
    //            status = "success"
    //        }
    //        catch (Exception e)
    //        {
    //            status = "false"
    //            e.printStackTrace()
    //        }
    //        render([status: status] as JSON)
    //    }

    /**
     * 发布预警列表*/
    def releasePriceFluctuationsWarning(Integer max)
    {
        params.max = Math.min(max ?: 10, 100)
        params.offset = params.offset ? params.offset.toInteger() : 0

        def city = params['city']
        def district = params['district']
        def residentialType = params['residentialType']

        def user = User.findById(springSecurityService.principal.id)
        //        def estateSql = " from Collateral c where c.type.code = 'estate' and c.status = 'Completed' and c.account.id in " + Account.FilterAccountSql(user) + " and c.id not in ( select r.collateral.id from RiskWarning r where r.type.code = '1' and r.isWarning = '1') "
        //        if (city && city !='-1')
        //        {
        //            estateSql += " and c.city.zoneNumber = '${city}' "
        //        }
        //        if (district && district !='-1')
        //
        //        {
        //            estateSql += " and c.district.zoneNumber = '${district}' "
        //        }
        //        if(residentialType){
        //            estateSql += " and c.estate.buildingType.id = ${residentialType} "
        //        }
        //        def sql1 = " select count(*) "+estateSql
        //        estateSql += " order by c.modifiedDate desc "
        //        def collateralList = Collateral.executeQuery(estateSql, [max: params.max, offset: params.offset]).asList()
        //        def collateralCount = Collateral.executeQuery(sql1)
        //        def districtList = District.findAllByParentAreaAndAreaLevel(City.findByZoneNumberAndAreaLevel(city, 2), 3)
        respond null, model: [collateralList: null, collateralCount: 0, districtList: null, params: params], view: 'releasePriceFluctuationsWarning'

    }

    /**
     * 单条发布预警*/
    //    def toReleaseWarning(Estate estate)
    //    {
    //        def status = ""
    //        //价值波动率
    //        def priceFluctuationsRatio = params["priceFluctuationsRatio"]
    //        try
    //        {
    //            estate.priceFluctuationsRatio = priceFluctuationsRatio
    //            estate.warningStatus = RiskWarningStatusDict.findByCode('2')
    //            estate.save flush: true
    //            status = "success"
    //        }
    //        catch (Exception e)
    //        {
    //            e.printStackTrace()
    //            status = "false"
    //        }
    //        render([status: status] as JSON)
    //    }

    /**
     * 多条发布预警*/
    def multitermReleaseWarning()
    {
        def status = ""
        //价值波动率
        def ids = params["ids"]
        //        try
        //        {
        //            def idList = new ArrayList()
        //            if (ids)
        //            {
        //                idList = ids.split(",")
        //            }
        //            idList?.each {
        //                def collateral = House.findById(Long.parseLong(it))
        //                //预警
        //                def type = RiskWarningTypeDict.findByCode("1")
        //                def state = RiskWarningStatusDict.findByCode("2")
        //                def riskWarning = RiskWarning.findByCollateralAndType(collateral, type)
        //                if (!riskWarning)
        //                {
        //                    riskWarning = new RiskWarning()
        //                }
        //                riskWarning.type = type
        //                riskWarning.collateral = collateral
        //                riskWarning.status = state
        //                if (riskWarning.validate())
        //                {
        //                    riskWarning.save()
        //                }
        //                else
        //                {
        //                    println riskWarning.errors
        //                }
        //            }
        //            status = "success"
        //        }
        //        catch (Exception e)
        //        {
        //            e.printStackTrace()
        //            status = "false"
        //        }
        render([status: status] as JSON)
    }

    def searchConditionSql(params, estateQueryParam)
    {
        //城市
        def city = params["city"]
        //行政区
        def district = params["district"]
        //房屋用途
        def residentialType = params["residentialType"]
        //价值波动率
        def priceFluctuationsRatio = params["priceFluctuationsRatio"]
        //小区id
        def communityId = params["communityId"]
        //        if (communityId)
        //        {
        //            def cityNumber = Estate.findByCommunityId(communityId)?.city?.zoneNumber
        //            if (cityNumber)
        //            {
        //                params['city'] = cityNumber
        //            }
        //            def districtNumber = Estate.findByCommunityId(communityId)?.district?.zoneNumber
        //            if (districtNumber)
        //            {
        //                params['district'] = districtNumber
        //            }
        //        }
        //
        //        def estateSql = " "
        //        if (city && city != "-1")
        //        {
        //            estateSql += " and e.city.zoneNumber = :city "
        //            estateQueryParam["city"] = city
        //        }
        //        if (district && district != "-1")
        //        {
        //            estateSql += " and e.district.zoneNumber = :district "
        //            estateQueryParam["district"] = district
        //        }
        //        if (residentialType && residentialType != '')
        //        {
        //            estateSql += " and e.estate.buildingType.code = :residentialType "
        //            estateQueryParam['residentialType'] = residentialType
        //        }
        //        if (priceFluctuationsRatio && priceFluctuationsRatio != '')
        //        {
        //            estateSql += " and e.estate.priceFluctuationsRatio = :priceFluctuationsRatio "
        //            estateQueryParam['priceFluctuationsRatio'] = priceFluctuationsRatio
        //        }

        return ""
    }

    def districtList()
    {
        if (params["city"] == '-1')
        {
            return ''
        }
        else
        {
            render([districtList: null] as JSON)
        }
    }

    // // 押品价值波动预警（组件内容）
    // def priceFluctuationsRatioInit()
    // {
    //     def user = User.findById(springSecurityService.principal.id)
    //     def sql = "select new map(c.id as id) from Collateral c left join c.estate e where c.status = 'Completed' and c.account.id in " + Account.FilterAccountSql(user)
    //     def result = Collateral.executeQuery(sql).asList()
    //     result?.each
    //             {
    //                 println it?.id
    //                 def collateral = Collateral.findById(it?.id)
    //                 println collateral
    //                 def estate = collateral?.estate
    //                 def param = [em: 1,
    //                              city: estate?.city?.name,
    //                              address: estate?.sourceAddress,
    //                              floor: estate?.sourceCurrentFloor,
    //                              totalFloor: estate?.sourceTotalFloor,
    //                              name:estate?.communityName,
    //                              square: estate?.buildArea]

    //                 //自动评估
    //                 def evaluateResult = apiService.evaluate(param)
    //                 def priceFluctuationsRatio = estate?.priceFluctuationsRatio?estate.priceFluctuationsRatio:new BigDecimal(0).setScale(4,BigDecimal.ROUND_HALF_UP)
    //                 //价值波动
    //                 if (evaluateResult.code == "0")
    //                 {
    //                     def latestEvaluatePrice = estate?.latestEvaluatePrice
    //                     def newEvaluatePrice = evaluateResult?.saleprice
    //                     if(latestEvaluatePrice){
    //                         priceFluctuationsRatio = new BigDecimal((newEvaluatePrice-latestEvaluatePrice)/latestEvaluatePrice).setScale(4,BigDecimal.ROUND_HALF_UP)
    //                     }
    //                     estate.latestEvaluateDate = new Date()
    //                     estate.latestEvaluatePrice = evaluateResult?.saleprice
    //                     estate.priceFluctuationsRatio = priceFluctuationsRatio
    //                     if (estate.validate())
    //                     {
    //                         estate.save()
    //                     }
    //                     else
    //                     {
    //                         println estate.errors
    //                     }
    //                     collateral.latestEvaluatePrice = estate.latestEvaluatePrice
    //                     collateral.latestEvaluateDate = estate.latestEvaluateDate
    //                     if (collateral.validate())
    //                     {
    //                         collateral.save()
    //                     }
    //                     else
    //                     {
    //                         println collateral.errors
    //                     }
    //                 }
    //                 //预警
    //                 def type = RiskWarningTypeDict.findByCode("1")
    //                 def status = RiskWarningStatusDict.findByCode("2")
    //                 def riskWarning = RiskWarning.findByCollateralAndType(collateral, type)
    //                 def valueRiseWeight = RiskWarningConfig.findByCode('1')?.minValue// 价值上升波动范围
    //                 def valueDeclineWeight = RiskWarningConfig.findByCode('2')?.minValue // 价值下降波动范围
    //                 if(priceFluctuationsRatio >= valueRiseWeight || priceFluctuationsRatio <= valueDeclineWeight){
    //                     if (!riskWarning)
    //                     {
    //                         riskWarning = new RiskWarning()
    //                     }
    //                     riskWarning.type = type
    //                     riskWarning.collateral = collateral
    //                     riskWarning.status = status
    //                     if (riskWarning.validate())
    //                     {
    //                         riskWarning.save()
    //                     }
    //                     else
    //                     {
    //                         println riskWarning.errors
    //                     }
    //                 }else{
    //                     if (riskWarning)
    //                     {
    //                         riskWarning.isWarning = false

    //                         if (riskWarning.validate())
    //                         {
    //                             riskWarning.save()
    //                         }
    //                         else
    //                         {
    //                             println riskWarning.errors
    //                         }
    //                     }

    //                 }

    //             }

    //     render result?.size()
    // }
    /**
     * 命中反欺诈*/
    def antiFraudWarning(Integer max)
    {
        def user = User.findById(springSecurityService.principal.id)

        def order = params["order"]
        def sort = params["sort"]
        def city = params["city"]
        def district = params["district"]
        def borrName = params['borrName']
        def borrIdCardNo = params["borrIdCardNo"]
        def serialNumber = params["serialNumber"]

        def mortgageList = new ArrayList()
        def mortgageQueryParam = new HashMap()
        //        String mortgageSql = " from Mortgage e where e.warningStatus.code in ('2', '3') and e.account.id in " + Account.FilterAccountSql(user)
        //        if (city && city != 'null' && city != '-1')
        //        {
        //            mortgageSql += " and e.account.city.zoneNumber = :city "
        //            mortgageQueryParam['city'] = city
        //        }
        //        if (district && district != 'null' && district != '-1')
        //        {
        //            mortgageSql += " and e.account.district.zoneNumber = :district "
        //            mortgageQueryParam['district'] = district
        //        }
        //        if (serialNumber && serialNumber != '')
        //        {
        //            mortgageSql += " and e.serialNumber = :serialNumber "
        //            mortgageQueryParam['serialNumber'] = serialNumber
        //        }
        //        if (borrName && borrName != '')
        //        {
        //            mortgageSql += " and e.borrName like :borrName "
        //            mortgageQueryParam['borrName'] = '%' + borrName + '%'
        //        }
        //        if (borrIdCardNo && borrIdCardNo != "")
        //        {
        //            mortgageSql += " and e.borrIdCardNo like :borrIdCardNo "
        //            mortgageQueryParam['borrIdCardNo'] = '%' + borrIdCardNo + '%'
        //        }
        //
        //        //查询总数
        //        String countSql = "select count(e.id) " + mortgageSql
        //        mortgageSql += " order by e.modifiedDate desc "
        //        mortgageList = Mortgage.executeQuery(mortgageSql, mortgageQueryParam, [max: params.max ?: 10, offset: params.offset ?: 0])
        //        def mortgageCount = Mortgage.executeQuery(countSql, mortgageQueryParam)
        //        def districtList = District.findAllByParentAreaAndAreaLevel(City.findByZoneNumberAndAreaLevel(city, 2), 3)
        respond mortgageList, model: [mortgageCount: 0, params: params, districtList: null], view: 'antiFraudWarning'
    }

    /**
     * 命中反欺诈处置*/
    //    def disposalAntiFraud(Mortgage mortgage)
    //    {
    //        def status = ""
    //        //预警状态
    //        def riskWarningStatusDict = RiskWarningStatusDict.findByCode('3')
    //        def dealType = RiskWarningDealTypeDict.findByCode("IsAntiFraud")
    //        try
    //        {
    //            mortgage.warningStatus = riskWarningStatusDict
    //            mortgage.dealType = dealType
    //            mortgage.save flush: true
    //            status = "success"
    //        }
    //        catch (Exception e)
    //        {
    //            status = "false"
    //            e.printStackTrace()
    //        }
    //        render([status: status] as JSON)
    //    }

    /**
     * 命中反欺诈删除*/
    //    def deleteAntiFraud(Mortgage mortgage)
    //    {
    //        def riskWarningStatusDict = RiskWarningStatusDict.findByCode('1')
    //        def status = ""
    //        try
    //        {
    //            mortgage.warningStatus = riskWarningStatusDict
    //            mortgage.dealType = null
    //            mortgage.save flush: true
    //            status = "success"
    //        }
    //        catch (Exception e)
    //        {
    //            status = "false"
    //            e.printStackTrace()
    //        }
    //        render([status: status] as JSON)
    //    }

    /**
     * 命中反欺诈发布*/
    def releaseAntiFraudWarning(Integer max)
    {
        def user = User.findById(springSecurityService.principal.id)

        def city = params["city"]
        def district = params["district"]
        def serialNumber = params["serialNumber"]
        def borrName = params['borrName']
        def borrIdCardNo = params["borrIdCardNo"]
        def mortgageList = new ArrayList()
        def mortgageQueryParam = new HashMap()
        //        String mortgageSql = " from Mortgage e where e.warningStatus.code = '1' and e.account.id in " + Account.FilterAccountSql(user)
        //        if (city && city != 'null' && city != '-1')
        //        {
        //            mortgageSql += " and e.account.city.zoneNumber = :city "
        //            mortgageQueryParam['city'] = city
        //        }
        //        if (district && district != 'null' && district != '-1')
        //        {
        //            mortgageSql += " and e.account.district.zoneNumber = :district "
        //            mortgageQueryParam['district'] = district
        //        }
        //        if (serialNumber && serialNumber != '')
        //        {
        //            mortgageSql += " and e.serialNumber = :serialNumber "
        //            mortgageQueryParam['serialNumber'] = serialNumber
        //        }
        //        if (borrName && borrName != '')
        //        {
        //            mortgageSql += " and e.borrName like :borrName "
        //            mortgageQueryParam['borrName'] = '%' + borrName + '%'
        //        }
        //        if (borrIdCardNo && borrIdCardNo != "")
        //        {
        //            mortgageSql += " and e.borrIdCardNo like :borrIdCardNo "
        //            mortgageQueryParam['borrIdCardNo'] = '%' + borrIdCardNo + '%'
        //        }
        //
        //        //查询总数
        //        String countSql = "select count(e.id) " + mortgageSql
        //        mortgageSql += " order by e.modifiedDate desc "
        //        mortgageList = Mortgage.executeQuery(mortgageSql, mortgageQueryParam, [max: params.max ?: 10, offset: params.offset ?: 0])
        //        def mortgageCount = Mortgage.executeQuery(countSql, mortgageQueryParam)
        //        def districtList = District.findAllByParentAreaAndAreaLevel(City.findByZoneNumberAndAreaLevel(city, 2), 3)
        respond mortgageList, model: [mortgageCount: 0, params: params, districtList: null], view: 'releaseAntiFraudWarning'
    }

    /**
     * 单条发布预警1*/
    //    def toReleaseWarning1(Mortgage mortgage)
    //    {
    //        def status = ""
    //        //预警状态
    //        def riskWarningStatusDict = RiskWarningStatusDict.findByCode('2')
    //        try
    //        {
    //            mortgage.warningStatus = riskWarningStatusDict
    //            mortgage.save flush: true
    //            status = "success"
    //
    //        }
    //        catch (Exception e)
    //        {
    //            e.printStackTrace()
    //            status = "false"
    //        }
    //        render([status: status] as JSON)
    //
    //    }

    /**
     * 多条发布预警1*/
    def multitermReleaseWarning1()
    {
        def status = ""
        //预警状态
        //        def riskWarningStatusDict = RiskWarningStatusDict.findByCode('2')
        //        def ids = params["ids"]
        //        try
        //        {
        //            def idList = new ArrayList()
        //            if (ids)
        //            {
        //                idList = ids.split(",")
        //            }
        //            idList?.each {
        //                def mortgage = Mortgage.findById(Long.parseLong(it))
        //                mortgage.warningStatus = riskWarningStatusDict
        //                mortgage.save flush: true
        //            }
        //            status = "success"
        //        }
        //        catch (Exception e)
        //        {
        //            e.printStackTrace()
        //            status = "false"
        //        }
        render([status: status] as JSON)

    }

    def riskWarningIndex()
    {
        def user = User.findById(springSecurityService.principal.id)

        //        // 价值波动数量
        //        def priceFluctuationsRatioSql = " select count(r.id) from RiskWarning r where r.type.code = '1' and r.isWarning = '1' and r.collateral.account.id in " + Account.FilterAccountSql(user)
        //        def priceFluctuationsRatioCount = RiskWarning.executeQuery(priceFluctuationsRatioSql)
        //        // 押品效期到期数量
        //        def effectiveMaturitySql = " select count(r.id) from RiskWarning r where r.type.code = '14' and r.isWarning = '1' and r.collateral.account.id in " + Account.FilterAccountSql(user)
        //        def effectiveMaturityCount = RiskWarning.executeQuery(effectiveMaturitySql)
        //        // 集中度预警数量数量
        //        def concentrationSql = " select count(r.id) from RiskWarning r where r.type.code = '7' and r.isWarning = '1' "
        //        def concentrationCount = RiskWarning.executeQuery(concentrationSql)
        //        // 楼盘风险预警数量
        //        def buildingScoreSql = " select count(r.id) from RiskWarning r where r.type.code = '15' and r.isWarning = '1' "
        //        def buildingScoreCount = RiskWarning.executeQuery(buildingScoreSql)
        //        // 覆盖率预警数量
        //        def collateralCoverageRateSql = " select count(r.id) from RiskWarning r where r.type.code = '10' and r.isWarning = '1' "
        //        def collateralCoverageRateCount = RiskWarning.executeQuery(collateralCoverageRateSql)
        //
        //        // 个人逾期/违约
        //        def contactOverdueCountSql = " select count(r.id) from RiskWarning r where r.type.code = '8' and r.isWarning = '1' "
        //        def contactOverdueCount = RiskWarning.executeQuery(contactOverdueCountSql)
        //
        //        // 反欺诈
        //        def antiFraudSql =  "select count(e.id) from Mortgage e where e.warningStatus.code in ('2', '3') and e.account.id in " + Account.FilterAccountSql(user)
        //        def antiFraudCount = Mortgage.executeQuery(antiFraudSql)
        //
        //        // 待办
        //        def roleSql = ""
        //        def roleList = UserRole.findAllByUser(user)*.role
        //        if (roleList)
        //        {
        //            String roleIdList = roleList*.id?.toString()
        //            roleSql += " and role.id in (" + roleIdList?.substring(1, roleIdList.lastIndexOf("]")) + ")"
        //        }
        //
        //        def estatePendingSql = "select count(c.id) from CollateralFlowStage f left join f.collateral c where f.stage.id = c.stage.id and f.id in (select flowStage.id from CollateralFlowStageRole where teamRole.code = 'Approval'" + roleSql + ") and c.status = 'Pending' and c.type.code = 'estate'"
        //        def estatePendingCount = House.executeQuery(estatePendingSql)
        respond user, model: [userAccount: user?.account, priceFluctuationsRatioCount: 0, antiFraudCount: 0, estatePendingCount: 0, effectiveMaturityCount: 0, concentrationCount: 0, buildingScoreCount: 0, collateralCoverageRateCount: 0, contactOverdueCount: 0]
    }

    /**
     * 集中度风险统计*/
    def concentrationRisk()
    {

    }

    //楼盘评分预警
    def buildingScoreWarning(Integer max)
    {
        params.max = Math.min(max ?: 10, 100)
        params.offset = params.offset ? params.offset.toInteger() : 0
        def address = params['address']
        def communityName = params['communityName']
        def status = params['status']
        def sql = "from RiskWarning r where r.type.code = '15' and r.isWarning = '1' "
        if (address)
        {
            sql += " and r.community.address like '%${address}%' "
        }
        if (communityName)
        {
            sql += " and r.community.communityName like '%${communityName}%' "
        }
        if (status)
        {
            sql += " and r.status.id = '${status}' "
        }
        def sql1 = " select count(*) " + sql
        sql += " order by r.modifiedDate desc "

        def riskWarningList = RiskWarning.executeQuery(sql, [max: params.max, offset: params.offset]).asList()
        def riskWarningCount = RiskWarning.executeQuery(sql1)
        respond riskWarningList, model: [riskWarningList: riskWarningList, riskWarningCount: riskWarningCount[0]]
    }

    /**
     * 前往流通性评估页面*/
    def buildingScoreWarningShow()
    {
        def zoneNumber = params['city']
        def communityId = Long.parseLong(params['id'])
        params.status = RiskWarning.findByCommunity(Community.findByCommunityId(communityId))?.status?.name
        //小区详情
        def community = apiService.community(zoneNumber, communityId)
        //流动性评分
        def score = scoreApiService.communityLiquidityScore(communityId.toString())
        //小区价格走势
        def rate = apiService.communityRate(zoneNumber, communityId.toString())
        //获取上月数据
        def listingCount = 0
        def saleCount = 0
        def averPrice = 0
        def month = apiService.communityLastMonthRate(zoneNumber, communityId.toString())
        if (month?.data?.echartDate?.size() > 0)
        {
            //获取挂牌案例数量
            listingCount = month?.data?.echartDate[0]?.numberCount ? month?.data?.echartDate[0]?.numberCount : 0
            //获取成交案例数量
            //暂时不用def saleCount = month?.data?.echartDate[0]?.saleCount ? month?.data?.echartDate[0]?.saleCount : 0
            //获取小区均价
            averPrice = month?.data?.echartDate[0]?.price ? month?.data?.echartDate[0]?.price : 0
        }
        println "score--" + score
        println "month--" + month
        println "rate--" + rate

        //小区1年内的小区价格走势
        def trendPriceCommunityData = []
        def trendPriceCommunityDate = []

        //小区1年内的挂牌量趋势
        def trendNetlistData = []
        def trendNetlistDate = []

        //小区1年内小区的交易量趋势
        def communityTrendSaleData = []
        def communityTrendSaleDate = []

        if (rate?.data?.echartDate)
        {
            rate?.data?.echartDate.each {
                trendPriceCommunityData.push(it?.price)
                trendPriceCommunityDate.push(it?.monthDate)
                trendNetlistData.push(it?.numberCount)
                trendNetlistDate.push(it?.monthDate)
                communityTrendSaleData.push(it?.saleCount)
                communityTrendSaleDate.push(it?.monthDate)
                println it?.saleCount
                saleCount = saleCount + it?.saleCount
            }

        }

        //查询权值
        def communityScoreWeight = CommunityScoreWeight.list().get(0)

        def closingWeight = communityScoreWeight.closingWeight
        // 成交率权重
        def listingWeight = communityScoreWeight.listingWeight
        // 挂牌率权重
        def dealAvgDayWeight = communityScoreWeight.dealAvgDayWeight
        // 成交周期权重
        def discountrateWeight = communityScoreWeight.discountrateWeight
        // 折价比权重
        def foreclosureTimesWeight = communityScoreWeight.foreclosureTimesWeight
        // 法拍次数权重

        //小区配套权值
        def ifSchoolZoneScoreWeight = communityScoreWeight.schoolDistrictsWeight
        def communityTrafficScoreWeight = communityScoreWeight.trafficWeight
        def houseAgeScoreWeight = communityScoreWeight.houseAgeWeight
        def communityHospitalScoreWeight = communityScoreWeight.hospitalWeight
        def communityMallScoreWeight = communityScoreWeight.mallWeight
        def communityGreeningrateScoreWeight = communityScoreWeight.afforestationWeight
        def communityPlotratioScoreWeight = communityScoreWeight.ratioWeight
        def communityParkScoreWeight = communityScoreWeight.parkWeight
        def communityPmfeeScoreWeight = communityScoreWeight.propertyFeeWeight
        def communitySupermarketScoreWeight = communityScoreWeight.superMarketWeight
        def communityBankScoreWeight = communityScoreWeight.bankWeight

        def scenicWeight = communityScoreWeight.scenicWeight
        def noisePullutionWeight = communityScoreWeight.noisePullutionWeight
        def airPullutionWeight = communityScoreWeight.airPullutionWeight

        //小区总分
        def liquidWeight = communityScoreWeight.liquidityWeight
        def surroundWeight = communityScoreWeight.assortWeight
        def natureWeight = communityScoreWeight.natureWeight

        //小区配套评分
        def ifSchoolZoneScore = 0
        def communityTrafficScore = 0
        def houseAgeScore = 0
        def communityHospitalScore = 0
        def communityMallScore = 0
        def communityGreeningrateScore = 0
        def communityPlotratioScore = 0
        def communityParkScore = 0
        def communityPmfeeScore = 0
        def communitySupermarketScore = 0
        def communityBankScore = 0

        //流动性评分
        def closingScore = 0
        def dealAvgDayScore = 0
        def listingScore = 0
        def discountrateScore = 0
        def foreclosureTimesScore = 0

        def scenicScore = 0
        def noisePullutionScore = 0
        def airPullutionScore = 0

        //小区配套总分
        def communitySurroundingScore = 0

        //小区流动性总分
        def liquidityScore = 0

        //小区自然总分
        def natureScore = 0

        def scoreArr = []
        def surroudArr = []
        def natureArr = []

        DecimalFormat df = new DecimalFormat("#.00")
        DecimalFormat df1 = new DecimalFormat("#.0")
        if (score?.closingScore)
        {
            //成交率评分
            closingScore = (score?.closingScore ? score?.closingScore : 0) * closingWeight
            //成交周期评分
            dealAvgDayScore = (score?.dealAverageDayScore ? score?.dealAverageDayScore : 0) * dealAvgDayWeight
            //挂牌率评分
            listingScore = (score?.listingScore ? score?.listingScore : 0) * listingWeight
            //折价比例评分（法拍计算）
            discountrateScore = (score?.discountrateScore ? score?.discountrateScore : 0) * discountrateWeight
            //法拍次数评分
            foreclosureTimesScore = (score?.foreclosureTimesScore ? score?.foreclosureTimesScore : 0) * foreclosureTimesWeight

            ifSchoolZoneScore = (score?.ifSchoolZoneScore ? score?.ifSchoolZoneScore : 0) * ifSchoolZoneScoreWeight
            communityTrafficScore = (score?.communityTrafficScore ? score?.communityTrafficScore : 0) * communityTrafficScoreWeight
            houseAgeScore = (score?.houseAgeScore ? score?.houseAgeScore : 0) * houseAgeScoreWeight
            communityHospitalScore = (score?.communityHospitalScore ? score?.communityHospitalScore : 0) * communityHospitalScoreWeight
            communityMallScore = (score?.communityMallScore ? score?.communityMallScore : 0) * communityMallScoreWeight
            communityGreeningrateScore = (score?.communityGreeningrateScore ? score?.communityGreeningrateScore : 0) * communityGreeningrateScoreWeight
            communityPlotratioScore = (score?.communityPlotratioScore ? score?.communityPlotratioScore : 0) * communityPlotratioScoreWeight
            communityParkScore = (score?.communityParkScore ? score?.communityParkScore : 0) * communityParkScoreWeight
            communityPmfeeScore = (score?.communityPmfeeScore ? score?.communityPmfeeScore : 0) * communityPmfeeScoreWeight
            communitySupermarketScore = (score?.communitySupermarketScore ? score?.communitySupermarketScore : 0) * communitySupermarketScoreWeight
            communityBankScore = (score?.communityBankScore ? score?.communityBankScore : 0) * communityBankScoreWeight

            scenicScore = (score?.communityRecentlyScenicScore ? score?.communityRecentlyScenicScore : 0) * scenicWeight
            noisePullutionScore = (score?.communityRecentlySubwayScore ? score?.communityRecentlySubwayScore : 0) * noisePullutionWeight
            airPullutionScore = (score?.communityRecentlyPollutionScore ? score?.communityRecentlyPollutionScore : 0) * airPullutionWeight

            communitySurroundingScore = ifSchoolZoneScore + communityTrafficScore + houseAgeScore + communityHospitalScore + communityMallScore + communityGreeningrateScore + communityPlotratioScore + communityParkScore + communityPmfeeScore + communitySupermarketScore + communityBankScore

            liquidityScore = closingScore + dealAvgDayScore + listingScore + discountrateScore + foreclosureTimesScore

            natureScore = scenicScore + noisePullutionScore + airPullutionScore

            scoreArr = "[" + df.format(score?.closingScore ? score?.closingScore : 0) + "," + df.format(score?.dealAverageDayScore ? score?.dealAverageDayScore : 0) + "," + df.format(score?.listingScore ? score?.listingScore : 0) + "," + df.format(score?.discountrateScore ? score?.discountrateScore : 0) + "," + df.format(score?.foreclosureTimesScore ? score?.foreclosureTimesScore : 0) + "]"
            surroudArr = "[" + df.format(score?.ifSchoolZoneScore ? score?.ifSchoolZoneScore : 0) + "," + df.format(score?.communityTrafficScore ? score?.communityTrafficScore : 0) + "," + df.format(score?.houseAgeScore ? score?.houseAgeScore : 0) + "," + df.format(score?.communityHospitalScore ? score?.communityHospitalScore : 0) + "," + df.format(score?.communityMallScore ? score?.communityMallScore : 0) + "," + df.format(score?.communityGreeningrateScore ? score?.communityGreeningrateScore : 0) + "," + df.format(score?.communityPlotratioScore ? score?.communityPlotratioScore : 0) + "," + df.format(score?.communityParkScore ? score?.communityParkScore : 0) + "," + df.format(score?.communityPmfeeScore ? score?.communityPmfeeScore : 0) + "," + df.format(score?.communitySupermarketScore ? score?.communitySupermarketScore : 0) + "," + df.format(score?.communityBankScore ? score?.communityBankScore : 0) + "]"
            natureArr = "[" + df.format(score?.communityRecentlyScenicScore ? score?.communityRecentlyScenicScore : 0) + "," + df.format(score?.communityRecentlySubwayScore ? score?.communityRecentlySubwayScore : 0) + "," + df.format(score?.communityRecentlyPollutionScore ? score?.communityRecentlyPollutionScore : 0) + "]"
            println surroudArr
        }

        def communityScore = liquidityScore * liquidWeight + communitySurroundingScore * surroundWeight + natureScore * natureWeight

        //查询所有押品数量
        def estateCount = Estate.executeQuery("select count(e.id) from Estate e where e.communityId = ${communityId} and e.account.id in " + Account.FilterAccountSql(User.findById(springSecurityService.principal.id)))

        //计算押品均价
        def estateList = Estate.executeQuery(" select unitPrice,loansBalance,loansEvaluateTotalPrice from Estate e where e.communityId = ${communityId} and e.account.id in " + Account.FilterAccountSql(User.findById(springSecurityService.principal.id)))
        //def list = sql.rows
        def totalUnitPrice = 0
        def sumLoansBalance = 0
        def sumLoansEvaluatePrice = 0
        def avgUnitPrice = 0
        def avgCltv = 0
        estateList.each {
            totalUnitPrice += it[0] ? it[0] : 0
            sumLoansBalance += it[1] ? it[1] : 0
            sumLoansEvaluatePrice += it[2] ? it[2] : 0
        }
        println community
        if (estateList && sumLoansEvaluatePrice != 0)
        {
            //押品均价
            avgUnitPrice = totalUnitPrice / estateList.size()
            //动态抵押率
            avgCltv = sumLoansBalance / sumLoansEvaluatePrice
        }
        //成交周期
        def saleCycle = score?.dealAverageDay
        respond liquidityScore,
                model: [liquidityScore: df1.format(liquidityScore),
                    communitySurroundingScore: df1.format(communitySurroundingScore),
                    natureScore: df1.format(natureScore),
                    communityScore: df1.format(communityScore),
                    communityId: communityId,
                    scoreArr: scoreArr,
                    surroudArr: surroudArr,
                    natureArr: natureArr,
                    community: null,
                    estateCount: estateCount[0],
                    avgUnitPrice: avgUnitPrice,
                    avgCltv: avgCltv,
                    listingCount: listingCount,
                    saleCount: saleCount,
                    saleCycle: saleCycle,
                    averPrice: averPrice,
                    trendPriceCommunityData: trendPriceCommunityData,
                    trendPriceCommunityDate: trendPriceCommunityDate,
                    trendNetlistData: trendNetlistData,
                    trendNetlistDate: trendNetlistDate,
                    communityTrendSaleData: communityTrendSaleData,
                    communityTrendSaleDate: communityTrendSaleDate,
                    score: score], view: "buildingScoreWarningShow"
    }

    /**
     * 人员关系预警*/
    def contactRelationsWarning()
    {
        def max = Math.min(params.max ? params.max.toInteger() : 8, 100)
        def offset = params.offset ? params.offset.toInteger() : 0

        def fullName = params["fullName"]
        def identityType = params["identityType"]
        def idNumber = params["idNumber"]
        def estateQueryParam = new HashMap()
        def sort = params["sort"]
        def order = params["order"]
        def address = params["address"]
        def debitCardNumber = params["debitCardNumber"]
        def creditRiskLevel = params["creditRiskLevel"]
        def creditScoreStart = params["creditScoreStart"]
        def creditScoreEnd = params["creditScoreEnd"]
        def cellphone = params["cellphone"]
        def user = User.findById(springSecurityService.principal.id)

        //        def contactSql = " from Contact e where e.account.id in " + Account.FilterAccountSql(user)
        //        def sql = " "
        //
        //        // def highList = CreditScoreRiskDimension.findByLabel("高风险")
        //        def highList = CreditScoreRiskDimension.findByOrderNumber("1")
        //        def maxValue = highList?.maxValue
        //        sql += " and e.creditScore <= :maxValue "
        //        estateQueryParam['maxValue'] = new Double(maxValue)
        //
        //        if (address && address != "")
        //        {
        //            sql += " and e.address like :address"
        //            estateQueryParam['address'] = '%' + address + '%'
        //        }
        //        if (debitCardNumber && debitCardNumber != "")
        //        {
        //            sql += " and e.debitCardNumber like :debitCardNumber"
        //            estateQueryParam['debitCardNumber'] = '%' + debitCardNumber + '%'
        //        }
        //        if (creditRiskLevel && creditRiskLevel != "")
        //        {
        //            def riskList = CreditScoreRiskDimension.list()
        //            riskList.each {
        //                if (it?.label == creditRiskLevel)
        //                {
        //                    def minScoreValue = it.minValue
        //                    def maxScoreValue = it.maxValue
        //                    sql += " and e.creditScore > :minScoreValue and e.creditScore <= :maxScoreValue "
        //                    estateQueryParam['minScoreValue'] = new Double(minScoreValue)
        //                    estateQueryParam['maxScoreValue'] = new Double(maxScoreValue)
        //                }
        //            }
        //        }
        //        if (cellphone && cellphone != "")
        //        {
        //            sql += " and e.cellphone like :cellphone"
        //            estateQueryParam['cellphone'] = '%' + cellphone + '%'
        //        }
        //        if (creditScoreStart && creditScoreStart != '')
        //        {
        //            sql += " and e.creditScore >= :creditScoreStart "
        //            estateQueryParam['creditScoreStart'] = new Double(creditScoreStart)
        //        }
        //        if (creditScoreEnd && creditScoreEnd != '')
        //        {
        //            sql += " and e.creditScore <= :creditScoreEnd "
        //            estateQueryParam['creditScoreEnd'] = new Double(creditScoreEnd)
        //        }
        //        if (fullName && fullName != "")
        //        {
        //            sql += " and e.fullName like :fullName"
        //            estateQueryParam['fullName'] = '%' + fullName + '%'
        //        }
        //        if (idNumber && idNumber != "")
        //        {
        //            sql += " and e.idNumber = :idNumber "
        //            estateQueryParam['idNumber'] = idNumber
        //        }
        //        if (identityType && identityType != "")
        //        {
        //            sql += " and e.identityType.id = :identityType "
        //            estateQueryParam['identityType'] = Long.parseLong(identityType)
        //        }
        //
        //        def countSql = " select count(e.id) from Contact e where e.account.id in " + Account.FilterAccountSql(user)
        //        countSql += sql
        //
        //        if (order && sort)
        //        {
        //            sql += " order by e.${sort} ${order}"
        //        }
        //        else
        //        {
        //            sql += " order by e.modifiedDate desc "
        //        }
        //        contactSql += sql
        //
        //        def contactList = Contact.executeQuery(contactSql, estateQueryParam, [max: max, offset: offset])
        //        def contactCount = Contact.executeQuery(countSql, estateQueryParam)
        respond null, model: [contactList: null, contactCount: 0, params: params]

    }

    /**个人拓扑关系图
     * */
    def contactRelationsWarningShow()
    {

    }

    /**个人信用等级预警
     * */
    def contactCreditLevelWarning()
    {
        def max = Math.min(params.max ? params.max.toInteger() : 4, 100)
        def offset = params.offset ? params.offset.toInteger() : 0

        def fullName = params["fullName"]
        def identityType = params["identityType"]
        def idNumber = params["idNumber"]
        def estateQueryParam = new HashMap()
        def sort = params["sort"]
        def order = params["order"]
        def address = params["address"]
        def debitCardNumber = params["debitCardNumber"]
        def creditRiskLevel = params["creditRiskLevel"]
        def creditScoreStart = params["creditScoreStart"]
        def creditScoreEnd = params["creditScoreEnd"]
        def cellphone = params["cellphone"]
        def user = User.findById(springSecurityService.principal.id)

        def contactSql = " from Contact e where e.account.id in " + Account.FilterAccountSql(user)
        def sql = " "

        if (address && address != "")
        {
            sql += " and e.address like :address"
            estateQueryParam['address'] = '%' + address + '%'
        }
        if (debitCardNumber && debitCardNumber != "")
        {
            sql += " and e.debitCardNumber like :debitCardNumber"
            estateQueryParam['debitCardNumber'] = '%' + debitCardNumber + '%'
        }
        if (creditRiskLevel && creditRiskLevel != "")
        {
            def riskList = CreditScoreRiskDimension.list()
            riskList.each {
                if (it?.label == creditRiskLevel)
                {
                    def minScoreValue = it.minValue
                    def maxScoreValue = it.maxValue
                    sql += " and e.creditScore > :minScoreValue and e.creditScore <= :maxScoreValue "
                    estateQueryParam['minScoreValue'] = new Double(minScoreValue)
                    estateQueryParam['maxScoreValue'] = new Double(maxScoreValue)
                }
            }
        }
        if (cellphone && cellphone != "")
        {
            sql += " and e.cellphone like :cellphone"
            estateQueryParam['cellphone'] = '%' + cellphone + '%'
        }
        if (creditScoreStart && creditScoreStart != '')
        {
            sql += " and e.creditScore >= :creditScoreStart "
            estateQueryParam['creditScoreStart'] = new Double(creditScoreStart)
        }
        if (creditScoreEnd && creditScoreEnd != '')
        {
            sql += " and e.creditScore <= :creditScoreEnd "
            estateQueryParam['creditScoreEnd'] = new Double(creditScoreEnd)
        }
        if (fullName && fullName != "")
        {
            sql += " and e.fullName like :fullName"
            estateQueryParam['fullName'] = '%' + fullName + '%'
        }
        if (idNumber && idNumber != "")
        {
            sql += " and e.idNumber = :idNumber "
            estateQueryParam['idNumber'] = idNumber
        }
        if (identityType && identityType != "")
        {
            sql += " and e.identityType.id = :identityType "
            estateQueryParam['identityType'] = Long.parseLong(identityType)
        }

        def countSql = " select count(e.id) from Contact e where e.account.id in " + Account.FilterAccountSql(user)
        countSql += sql

        //        if (order && sort)
        //        {
        //           sql += " order by e.${sort} ${order}"
        //        }
        //        else
        //        {
        sql += " order by e.fullName desc "
        //        }
        contactSql += sql

        def contactList = Contact.executeQuery(contactSql, estateQueryParam, [max: max, offset: offset])
        def contactCount = Contact.executeQuery(countSql, estateQueryParam)
        respond contactList, model: [contactList: contactList, contactCount: contactCount[0], params: params], view: 'contactCreditLevelWarning'
    }

    //个人信用等级预警详情
    def contactCreditLevelWarningShow(Contact contact)
    {

        respond contact
    }

    //舆情预警
    def publicOpinionWarning()
    {
    }

    //舆情预警
    def publicOpinionShow()
    {
        def type = params['id']
        respond true, view: 'publicOpinionShow' + type
    }

    //逾期/违约（企业）
    def accountOverdueWarning()
    {
        def max = Math.min(params.max ? params.max.toInteger() : 4, 100)
        def offset = params.offset ? params.offset.toInteger() : 0
        //城市
        def city = params["city"]
        //行政区
        def district = params["district"]
        //注册资金
        def registeredCapitalStart = params["registeredCapitalStart"]
        //注册资金
        def registeredCapitalEnd = params["registeredCapitalEnd"]
        //信用评级
        def creditLevel = params["creditLevel"]
        //企业名称
        def name = params["name"]
        //经营状态
        def operatingState = params["operatingState"]
        //单位性质
        def unitNature = params["unitNature"]
        def estateQueryParam = new HashMap()
        def sort = params["sort"]
        def order = params["order"]

        def user = User.findById(springSecurityService.principal.id)
        def estateSql = " from Account e where e.type.code = 'MortgageAccount' and e.bankAccount.id in " + Account.FilterAccountSql(user)
        def sql = " "
        if (name && name != "")
        {
            sql += " and e.name like :name"
            estateQueryParam['name'] = '%' + name + '%'
        }
        if (city && city != "-1")
        {
            sql += " and e.city.zoneNumber = :city "
            estateQueryParam['city'] = city
        }
        if (district && district != "-1")
        {
            sql += " and e.district.zoneNumber = :district "
            estateQueryParam['district'] = district
        }
        if (registeredCapitalStart && registeredCapitalStart != "")
        {
            sql += "and e.registeredCapital >= :registeredCapitalStart "
            estateQueryParam['registeredCapitalStart'] = new BigDecimal(registeredCapitalStart) * 10000
        }
        if (registeredCapitalEnd && registeredCapitalEnd != "")
        {
            sql += "and e.registeredCapital <= :registeredCapitalEnd "
            estateQueryParam['registeredCapitalEnd'] = new BigDecimal(registeredCapitalEnd) * 10000
        }
        if (creditLevel && creditLevel != "")
        {
            sql += " and e.creditLevel like :creditLevel "
            estateQueryParam['creditLevel'] = "%" + creditLevel + "%"
        }
        if (operatingState && operatingState != "")
        {
            sql += " and e.operatingState = :operatingState "
            estateQueryParam['operatingState'] = operatingState
        }
        if (unitNature && unitNature != "")
        {
            sql += " and e.unitNature.id = :unitNature "
            estateQueryParam['unitNature'] = Long.parseLong(unitNature)
        }

        def countSql = " select count(e.id) from Account e where e.type.code = 'MortgageAccount' and e.bankAccount.id in " + Account.FilterAccountSql(user)
        countSql += sql

        if (order && sort)
        {
            sql += " order by e.${sort} ${order}"
        }
        else
        {
            sql += " order by e.modifiedDate desc "
        }
        estateSql += sql

        def accountList = Account.executeQuery(estateSql, estateQueryParam, [max: max, offset: offset])
        def accountCount = Account.executeQuery(countSql, estateQueryParam)
        respond accountList, model: [accountCount: accountCount[0], params: params]
    }

    //逾期/违约（对公）详情
    def accountOverdueWarningShow()
    {

    }

    //逾期/违约（个人）
    def contactOverdueWarning()
    {
        def max = Math.min(params.max ? params.max.toInteger() : 10, 100)
        def offset = params.offset ? params.offset.toInteger() : 0
        def user = User.findById(springSecurityService.principal.id)

        def fullName = params['fullName']
        def identityType = params['identityType']
        def idNumber = params['idNumber']
        def cellphone = params['cellphone']
        def defaultStart = params['defaultStart']
        def defaultEnd = params['defaultEnd']
        def overdueStart = params['overdueStart']
        def overdueEnd = params['overdueEnd']
        def disposalMethod = params['disposalMethod']
        def serialNumber = params['serialNumber']
        def stage = params['stage']

        def sql = "from RiskWarning r where r.type.code = '8' and r.isWarning = '1'"
        if (fullName)
        {
            sql += " and r.mortgage.mortgageContact.fullName like '%${fullName}%'"
        }
        if (identityType)
        {
            sql += " and r.mortgage.mortgageContact.identityType.id = ${identityType}"
        }
        if (idNumber)
        {
            sql += " and r.mortgage.mortgageContact.idNumber like '%${idNumber}%'"
        }
        if (cellphone)
        {
            sql += " and r.mortgage.mortgageContact.cellphone like '%${cellphone}%'"
        }
        if (defaultStart && defaultStart != "")
        {
            sql += " and r.mortgage.curDefaultingDuration >= ${defaultStart}"
        }
        if (defaultEnd && defaultEnd != "")
        {
            sql += " and r.mortgage.curDefaultingDuration <= ${defaultEnd}"
        }
        if (overdueStart && overdueStart != "")
        {
            sql += " and r.mortgage.curOverdueDuration >= ${overdueStart}"
        }
        if (overdueEnd && overdueEnd != "")
        {
            sql += " and r.mortgage.curOverdueDuration <= ${overdueEnd}"
        }
        if (disposalMethod)
        {
            sql += " and r.disposalMethod.id = ${disposalMethod}"
        }
        if (stage)
        {
            sql += " and r.stage.id = ${stage}"
        }
        if (serialNumber)
        {
            sql += " and r.mortgage.serialNumber like '${serialNumber}'"
        }
        def sql1 = " select count(*) " + sql
        sql += " order by r.modifiedDate desc "

        def riskWarningList = RiskWarning.executeQuery(sql, [max: max, offset: offset]).asList()
        def riskWarningCount = RiskWarning.executeQuery(sql1)
        respond riskWarningList, model: [riskWarningList: riskWarningList, riskWarningCount: riskWarningCount[0]]
    }

    // 催收列表
    // def overdueCollectionIndex()
    // {
    //     def max = Math.min(params.max ? params.max.toInteger() : 10, 100)
    //     def offset = params.offset ? params.offset.toInteger() : 0
    //     def user = User.findById(springSecurityService.principal.id)

    //     def fullName = params['fullName']
    //     def identityType = params['identityType']
    //     def idNumber = params['idNumber']
    //     def cellphone = params['cellphone']
    //     def defaultStart = params['defaultStart']
    //     def defaultEnd = params['defaultEnd']
    //     def overdueStart = params['overdueStart']
    //     def overdueEnd = params['overdueEnd']
    //     def disposalDepartment = params['disposalDepartment']
    //     def stage = params['stage']

    //     def roleSql = ""
    //     def roleList = UserRole.findAllByUser(user)*.role
    //     if (roleList)
    //     {
    //         String roleIdList = roleList*.id?.toString()
    //         roleSql += " and role.id in (" + roleIdList?.substring(1, roleIdList.lastIndexOf("]")) + ")"
    //     }

    //     def riskWarningSql = "select f.riskWarning from RiskWarningFlowStage f left join f.riskWarning c where c.type.code = '8' and c.isWarning = '1' and f.stage.id = c.stage.id and f.id in (select flowStage.id from RiskWarningFlowStageRole where teamRole.code = 'Approval'" + roleSql + ")"
    //     def riskWarningList1 = RiskWarningFlowStage.executeQuery(riskWarningSql, [max: max, offset: offset])
    //     if (riskWarningList1[0]?.disposalDepartment && riskWarningList1[0]?.stage?.code == '13')
    //     {
    //         riskWarningSql += " and c.disposalDepartment.id = ${user?.department?.id}"
    //     }
    //     if (riskWarningList1[0]?.disposalUser && riskWarningList1[0]?.stage?.code == '16')
    //     {
    //         riskWarningSql += " and c.disposalUser.id = ${user?.id}"
    //     }

    //     // 所有催收列表
    //     if (params['flag'])
    //     {
    //         riskWarningSql = "from RiskWarning c where c.type.code = '8' and c.isWarning = '1' and c.disposalMethod.code = '3'"
    //     }

    //     def sql = " "
    //     if (fullName)
    //     {
    //         sql += " and c.mortgage.mortgageContact.fullName like '%${fullName}%'"
    //     }
    //     if (identityType)
    //     {
    //         sql += " and c.mortgage.mortgageContact.identityType.id = ${identityType}"
    //     }
    //     if (idNumber)
    //     {
    //         sql += " and c.mortgage.mortgageContact.idNumber like '%${idNumber}%'"
    //     }
    //     if (cellphone)
    //     {
    //         sql += " and c.mortgage.mortgageContact.cellphone like '%${cellphone}%'"
    //     }
    //     if (defaultStart && defaultStart != "")
    //     {
    //         sql += " and c.mortgage.curDefaultingDuration >= ${defaultStart}"
    //     }
    //     if (defaultEnd && defaultEnd != "")
    //     {
    //         sql += " and c.mortgage.curDefaultingDuration <= ${defaultEnd}"
    //     }
    //     if (overdueStart && overdueStart != "")
    //     {
    //         sql += " and c.mortgage.curOverdueDuration >= ${overdueStart}"
    //     }
    //     if (overdueEnd && overdueEnd != "")
    //     {
    //         sql += " and c.mortgage.curOverdueDuration <= ${overdueEnd}"
    //     }
    //     if (disposalDepartment)
    //     {
    //         sql += " and c.disposalDepartment.id = ${disposalDepartment}"
    //     }
    //     if (stage)
    //     {
    //         sql += " and c.stage.id = ${stage}"
    //     }

    //     def countSql = "select count(c.id) from RiskWarningFlowStage f left join f.riskWarning c where c.type.code = '8' and c.isWarning = '1' and f.stage.id = c.stage.id and f.id in (select flowStage.id from RiskWarningFlowStageRole where teamRole.code = 'Approval'" + roleSql + ")" + sql
    //     if (params['flag'])
    //     {
    //         countSql = "select count(c.id) " + riskWarningSql
    //     }
    //     sql += " order by c.modifiedDate desc "

    //     println "riskWarningSql:" + riskWarningSql + sql
    //     println "countSql:" + countSql
    //     def riskWarningList = RiskWarningFlowStage.executeQuery(riskWarningSql + sql, [max: max, offset: offset])
    //     def riskWarningCount = RiskWarningFlowStage.executeQuery(countSql)

    //     respond riskWarningList, model: [riskWarningList: riskWarningList, riskWarningCount: riskWarningCount[0]]
    // }

    def contactOverdueWarningIndex()
    {
        def max = Math.min(params.max ? params.max.toInteger() : 10, 100)
        def offset = params.offset ? params.offset.toInteger() : 0
        def user = User.findById(springSecurityService.principal.id)

        def fullName = params['fullName']
        def identityType = params['identityType']
        def idNumber = params['idNumber']
        def cellphone = params['cellphone']
        def defaultStart = params['defaultStart']
        def defaultEnd = params['defaultEnd']
        def overdueStart = params['overdueStart']
        def overdueEnd = params['overdueEnd']
        def disposalDepartment = params['disposalDepartment']
        def serialNumber = params['serialNumber']
        def stage = params['stage']

        def roleSql = ""
        def roleList = UserRole.findAllByUser(user)*.role
        /*if (roleList)
        {
            String roleIdList = roleList*.id?.toString()
            roleSql += " and role.id in (" + roleIdList?.substring(1, roleIdList.lastIndexOf("]")) + ")"
        }

        def riskWarningSql = "select f.riskWarning from RiskWarningFlowStage f left join f.riskWarning c where c.type.code = '8' and c.isWarning = '1' and f.stage.id = c.stage.id and f.id in (select flowStage.id from RiskWarningFlowStageRole where teamRole.code = 'Approval'" + roleSql + ")"
        def riskWarningList1 = RiskWarningFlowStage.executeQuery(riskWarningSql, [max: max, offset: offset])
        if (riskWarningList1[0]?.disposalDepartment && riskWarningList1[0]?.stage?.code == '13')
        {
            riskWarningSql += " and c.disposalDepartment.id = ${user?.department?.id}"
        }
        if (riskWarningList1[0]?.disposalUser && riskWarningList1[0]?.stage?.code == '16')
        {
            riskWarningSql += " and c.disposalUser.id = ${user?.id}"
        }

        // 所有催收列表
        if (params['flag'])
        {
            riskWarningSql = "from RiskWarning c where c.type.code = '8' and c.isWarning = '1' and c.disposalMethod.code = '3'"
        }

        def sql = " "
        if (fullName)
        {
            sql += " and c.mortgage.mortgageContact.fullName like '%${fullName}%'"
        }
        if (identityType)
        {
            sql += " and c.mortgage.mortgageContact.identityType.id = ${identityType}"
        }
        if (idNumber)
        {
            sql += " and c.mortgage.mortgageContact.idNumber like '%${idNumber}%'"
        }
        if (cellphone)
        {
            sql += " and c.mortgage.mortgageContact.cellphone like '%${cellphone}%'"
        }
        if (defaultStart && defaultStart != "")
        {
            sql += " and c.mortgage.curDefaultingDuration >= ${defaultStart}"
        }
        if (defaultEnd && defaultEnd != "")
        {
            sql += " and c.mortgage.curDefaultingDuration <= ${defaultEnd}"
        }
        if (overdueStart && overdueStart != "")
        {
            sql += " and c.mortgage.curOverdueDuration >= ${overdueStart}"
        }
        if (overdueEnd && overdueEnd != "")
        {
            sql += " and c.mortgage.curOverdueDuration <= ${overdueEnd}"
        }
        if (disposalDepartment)
        {
            sql += " and c.disposalDepartment.id = ${disposalDepartment}"
        }
        if (stage)
        {
            sql += " and c.stage.id = ${stage}"
        }
        if (serialNumber)
        {
            sql += " and c.mortgage.serialNumber like '${serialNumber}'"
        }
        def countSql = "select count(c.id) from RiskWarningFlowStage f left join f.riskWarning c where c.type.code = '8' and c.isWarning = '1' and f.stage.id = c.stage.id and f.id in (select flowStage.id from RiskWarningFlowStageRole where teamRole.code = 'Approval'" + roleSql + ")" + sql
        if (params['flag'])
        {
            countSql = "select count(c.id) " + riskWarningSql
        }
        sql += " order by c.modifiedDate desc "

        println "riskWarningSql:" + riskWarningSql + sql
        println "countSql:" + countSql
        def riskWarningList = RiskWarningFlowStage.executeQuery(riskWarningSql + sql, [max: max, offset: offset])
        def riskWarningCount = RiskWarningFlowStage.executeQuery(countSql)
*/
        respond null, model: [riskWarningList: null, riskWarningCount: 0]
    }

    // 诉讼列表
    // def overdueLitigationIndex()
    // {
    //     def max = Math.min(params.max ? params.max.toInteger() : 10, 100)
    //     def offset = params.offset ? params.offset.toInteger() : 0
    //     def user = User.findById(springSecurityService.principal.id)

    //     def fullName = params['fullName']
    //     def identityType = params['identityType']
    //     def idNumber = params['idNumber']
    //     def cellphone = params['cellphone']
    //     def defaultStart = params['defaultStart']
    //     def defaultEnd = params['defaultEnd']
    //     def overdueStart = params['overdueStart']
    //     def overdueEnd = params['overdueEnd']
    //     def disposalDepartment = params['disposalDepartment']
    //     def stage = params['stage']

    //     def roleSql = ""
    //     def roleList = UserRole.findAllByUser(user)*.role
    //     if (roleList)
    //     {
    //         String roleIdList = roleList*.id?.toString()
    //         roleSql += " and role.id in (" + roleIdList?.substring(1, roleIdList.lastIndexOf("]")) + ")"
    //     }

    //     def riskWarningSql = "select f.riskWarning from RiskWarningFlowStage f left join f.riskWarning c where c.type.code = '8' and c.isWarning = '1' and f.stage.id = c.stage.id and f.id in (select flowStage.id from RiskWarningFlowStageRole where teamRole.code = 'Approval'" + roleSql + ")"
    //     // 所有催收列表
    //     if (params['flag'])
    //     {
    //         riskWarningSql = "from RiskWarning c where c.type.code = '8' and c.isWarning = '1' and c.disposalMethod.code in ('1', '2')"
    //     }
    //     def sql = " "
    //     if (fullName)
    //     {
    //         sql += " and c.mortgage.mortgageContact.fullName like '%${fullName}%'"
    //     }
    //     if (identityType)
    //     {
    //         sql += " and c.mortgage.mortgageContact.identityType.id = ${identityType}"
    //     }
    //     if (idNumber)
    //     {
    //         sql += " and c.mortgage.mortgageContact.idNumber like '%${idNumber}%'"
    //     }
    //     if (cellphone)
    //     {
    //         sql += " and c.mortgage.mortgageContact.cellphone like '%${cellphone}%'"
    //     }
    //     if (defaultStart && defaultStart != "")
    //     {
    //         sql += " and c.mortgage.curDefaultingDuration >= ${defaultStart}"
    //     }
    //     if (defaultEnd && defaultEnd != "")
    //     {
    //         sql += " and c.mortgage.curDefaultingDuration <= ${defaultEnd}"
    //     }
    //     if (overdueStart && overdueStart != "")
    //     {
    //         sql += " and c.mortgage.curOverdueDuration >= ${overdueStart}"
    //     }
    //     if (overdueEnd && overdueEnd != "")
    //     {
    //         sql += " and c.mortgage.curOverdueDuration <= ${overdueEnd}"
    //     }
    //     if (disposalDepartment)
    //     {
    //         sql += " and c.disposalDepartment.id = ${disposalDepartment}"
    //     }
    //     if (stage)
    //     {
    //         sql += " and c.stage.id = ${stage}"
    //     }

    //     def countSql = "select count(c.id) from RiskWarningFlowStage f left join f.riskWarning c where c.type.code = '8' and c.isWarning = '1' and f.stage.id = c.stage.id and f.id in (select flowStage.id from RiskWarningFlowStageRole where teamRole.code = 'Approval'" + roleSql + ")" + sql
    //     if (params['flag'])
    //     {
    //         countSql = "select count(c.id) " + riskWarningSql
    //     }
    //     sql += " order by c.modifiedDate desc "

    //     def riskWarningList = RiskWarningFlowStage.executeQuery(riskWarningSql + sql, [max: max, offset: offset])
    //     def riskWarningCount = RiskWarningFlowStage.executeQuery(countSql)

    //     respond riskWarningList, model: [riskWarningList: riskWarningList, riskWarningCount: riskWarningCount[0]]
    // }

    //逾期/违约（个人）详情
    def contactOverdueWarningShow(RiskWarning riskWarning)
    {
        //        def mortgage = riskWarning?.mortgage
        //        def user = User.findById(springSecurityService.principal.id)
        //        def flowStage = RiskWarningFlowStage.findByRiskWarningAndStage(riskWarning, riskWarning?.stage)
        //        def roleSql = ""
        //        def roleList = UserRole.findAllByUser(user)*.role
        //        if (roleList)
        //        {
        //            String roleIdList = roleList*.id?.toString()
        //            roleSql += " and role.id in (" + roleIdList?.substring(1, roleIdList.lastIndexOf("]")) + ")"
        //        }
        //        def editRoleFlag = false
        //        def approveRoleFlag = false
        //        if (flowStage)
        //        {
        //            editRoleFlag = RiskWarningFlowStageRole.find("from RiskWarningFlowStageRole where flowStage.id = ? and teamRole.id = ? " + roleSql, [flowStage?.id, TeamRole.EDIT()?.id]) && true
        //            approveRoleFlag = RiskWarningFlowStageRole.find("from RiskWarningFlowStageRole where flowStage.id = ? and teamRole.id = ? " + roleSql, [flowStage?.id, TeamRole.APPROVAL()?.id]) && true
        //        }
        //
        //        def layout = RiskWarningFlowStage.findByRiskWarningAndStage(riskWarning, riskWarning?.stage)?.layout?.name
        respond null, model: [editRoleFlag: true, approveRoleFlag: true, params: params, riskWarning: riskWarning, contact: null]
    }

    //信用等级预警（企业）
    def accountCreditLevelWarning()
    {
        def max = Math.min(params.max ? params.max.toInteger() : 10, 100)
        def offset = params.offset ? params.offset.toInteger() : 0
        //城市
        def city = params["city"]
        //行政区
        def district = params["district"]
        //注册资金
        def registeredCapitalStart = params["registeredCapitalStart"]
        //注册资金
        def registeredCapitalEnd = params["registeredCapitalEnd"]
        //信用评级
        def creditLevel = params["creditLevel"]
        //企业名称
        def name = params["name"]
        //经营状态
        def operatingState = params["operatingState"]
        //单位性质
        def unitNature = params["unitNature"]
        def estateQueryParam = new HashMap()
        def sort = params["sort"]
        def order = params["order"]

        def user = User.findById(springSecurityService.principal.id)
        //        def estateSql = " from Account e where e.type.code = 'MortgageAccount' and e.bankAccount.id in " + Account.FilterAccountSql(user)
        //        def sql = " "
        //        if (name && name != "")
        //        {
        //            sql += " and e.name like :name"
        //            estateQueryParam['name'] = '%' + name + '%'
        //        }
        //        if (city && city != "-1")
        //        {
        //            sql += " and e.city.zoneNumber = :city "
        //            estateQueryParam['city'] = city
        //        }
        //        if (district && district != "-1")
        //        {
        //            sql += " and e.district.zoneNumber = :district "
        //            estateQueryParam['district'] = district
        //        }
        //        if (registeredCapitalStart && registeredCapitalStart != "")
        //        {
        //            sql += "and e.registeredCapital >= :registeredCapitalStart "
        //            estateQueryParam['registeredCapitalStart'] = new BigDecimal(registeredCapitalStart) * 10000
        //        }
        //        if (registeredCapitalEnd && registeredCapitalEnd != "")
        //        {
        //            sql += "and e.registeredCapital <= :registeredCapitalEnd "
        //            estateQueryParam['registeredCapitalEnd'] = new BigDecimal(registeredCapitalEnd) * 10000
        //        }
        //        if (creditLevel && creditLevel != "")
        //        {
        //            sql += " and e.creditLevel like :creditLevel "
        //            estateQueryParam['creditLevel'] = "%" + creditLevel + "%"
        //        }
        //        if (operatingState && operatingState != "")
        //        {
        //            sql += " and e.operatingState = :operatingState "
        //            estateQueryParam['operatingState'] = operatingState
        //        }
        //        if (unitNature && unitNature != "")
        //        {
        //            sql += " and e.unitNature.id = :unitNature "
        //            estateQueryParam['unitNature'] = Long.parseLong(unitNature)
        //        }
        //
        //        def countSql = " select count(e.id) from Account e where e.type.code = 'MortgageAccount' and e.bankAccount.id in " + Account.FilterAccountSql(user)
        //        countSql += sql
        //
        //        if (order && sort)
        //        {
        //            sql += " order by e.${sort} ${order}"
        //        }
        //        else
        //        {
        //            sql += " order by e.modifiedDate desc "
        //        }
        //        estateSql += sql
        //
        //        def accountList = Account.executeQuery(estateSql, estateQueryParam, [max: max, offset: offset])
        //        def accountCount = Account.executeQuery(countSql, estateQueryParam)
        respond null, model: [accountCount: 0, params: params]

    }

    def accountCreditLevelWarningShow()
    {

    }

    def contactRiskWarning()
    {
        def max = Math.min(params.max ? params.max.toInteger() : 10, 100)
        def offset = params.offset ? params.offset.toInteger() : 0

        def fullName = params["fullName"]
        def identityType = params["identityType"]
        def idNumber = params["idNumber"]
        def estateQueryParam = new HashMap()
        def sort = params["sort"]
        def order = params["order"]
        def address = params["address"]
        def debitCardNumber = params["debitCardNumber"]
        def creditRiskLevel = params["creditRiskLevel"]
        def creditScoreStart = params["creditScoreStart"]
        def creditScoreEnd = params["creditScoreEnd"]
        def cellphone = params["cellphone"]
        def batch = params["batch"]
        def user = User.findById(springSecurityService.principal.id)

        //        def riskSql = "from ContactRiskWarningDisposition c where 1=1"
        //        def riskWarningStatus = params['riskWarningStatus']
        //        if (riskWarningStatus)
        //        {
        //            riskSql += " and c.status = '${riskWarningStatus}'"
        //        }
        //        def riskWarningDispositionType = params['riskWarningDispositionType']
        //        if (riskWarningDispositionType)
        //        {
        //            riskSql += " and c.type.id = ${riskWarningDispositionType}"
        //        }
        //
        //        def dispositionSql = ""
        //        if (riskWarningStatus || riskWarningDispositionType)
        //        {
        //            def dispositionList = ContactRiskWarningDisposition.executeQuery(riskSql)*.contact.unique()
        //            if (dispositionList)
        //            {
        //                String dispositionIdList = dispositionList*.id?.toString()
        //                dispositionSql += " and e.id in (" + dispositionIdList?.substring(1, dispositionIdList.lastIndexOf("]")) + ")"
        //            }
        //            else
        //            {
        //                dispositionSql += " and e.id in ('-1')"
        //            }
        //        }
        //
        //        def contactSql = " from Contact e where e.account.id in " + Account.FilterAccountSql(user)
        //        def sql = " "
        //        if (dispositionSql)
        //        {
        //            sql += dispositionSql
        //        }
        //        // def highList = CreditScoreRiskDimension.findByLabel("高风险")
        //        def highList = CreditScoreRiskDimension.findByOrderNumber("1")
        //        def maxValue = highList?.maxValue
        //        sql += " and e.creditScore <= :maxValue "
        //        estateQueryParam['maxValue'] = new Double(maxValue)
        //
        //        if (address && address != "")
        //        {
        //            sql += " and e.address like :address"
        //            estateQueryParam['address'] = '%' + address + '%'
        //        }
        //        if (debitCardNumber && debitCardNumber != "")
        //        {
        //            sql += " and e.debitCardNumber like :debitCardNumber"
        //            estateQueryParam['debitCardNumber'] = '%' + debitCardNumber + '%'
        //        }
        //        if (creditRiskLevel && creditRiskLevel != "")
        //        {
        //            def riskList = CreditScoreRiskDimension.list()
        //            riskList.each {
        //                if (it?.label == creditRiskLevel)
        //                {
        //                    def minScoreValue = it.minValue
        //                    def maxScoreValue = it.maxValue
        //                    sql += " and e.creditScore > :minScoreValue and e.creditScore <= :maxScoreValue "
        //                    estateQueryParam['minScoreValue'] = new Double(minScoreValue)
        //                    estateQueryParam['maxScoreValue'] = new Double(maxScoreValue)
        //                }
        //            }
        //        }
        //        if (cellphone && cellphone != "")
        //        {
        //            sql += " and e.cellphone like :cellphone"
        //            estateQueryParam['cellphone'] = '%' + cellphone + '%'
        //        }
        //        if (creditScoreStart && creditScoreStart != '')
        //        {
        //            sql += " and e.creditScore >= :creditScoreStart "
        //            estateQueryParam['creditScoreStart'] = new Double(creditScoreStart)
        //        }
        //        if (creditScoreEnd && creditScoreEnd != '')
        //        {
        //            sql += " and e.creditScore <= :creditScoreEnd "
        //            estateQueryParam['creditScoreEnd'] = new Double(creditScoreEnd)
        //        }
        //        if (fullName && fullName != "")
        //        {
        //            sql += " and e.fullName like :fullName"
        //            estateQueryParam['fullName'] = '%' + fullName + '%'
        //        }
        //        if (idNumber && idNumber != "")
        //        {
        //            sql += " and e.idNumber = :idNumber "
        //            estateQueryParam['idNumber'] = idNumber
        //        }
        //        if (identityType && identityType != "")
        //        {
        //            sql += " and e.identityType.id = :identityType "
        //            estateQueryParam['identityType'] = Long.parseLong(identityType)
        //        }
        //        if (batch && batch != "")
        //        {
        //            sql += " and e.batch.id = :batch "
        //            estateQueryParam['batch'] = Long.parseLong(batch)
        //        }
        //
        //        def countSql = " select count(e.id) from Contact e where e.account.id in " + Account.FilterAccountSql(user)
        //        countSql += sql
        //
        //        if (order && sort)
        //        {
        //            sql += " order by e.${sort} ${order}"
        //        }
        //        else
        //        {
        //            sql += " order by e.modifiedDate desc "
        //        }
        //        contactSql += sql
        //        def contactList = Contact.executeQuery(contactSql, estateQueryParam, [max: max, offset: offset])
        //        def contactCount = Contact.executeQuery(countSql, estateQueryParam)
        respond null, model: [contactList: null, contactCount: 0, params: params], view: 'contactRiskWarning'
    }

    def contactRiskWarningShow(Contact contact)
    {
        //        def mortgageList = MortgageContact.findAllByContact(contact)*.mortgage?.unique()
        respond contact, model: [mortgageList: null, contactDetail: contact], view: 'contactRiskWarningShow'
    }

    @Transactional
    //    def contactRiskWarningDisposal(ContactRiskWarningDisposition contactRiskWarningDisposition){
    //        def contactIds = params["contactIds"]
    //        def targetUri = request.getHeader("referer")
    //        if(contactIds){
    //            def idList = contactIds.split(",")
    //            println "===========idList="+idList
    //            idList?.each {
    //                Contact contact = Contact.findById(Long.parseLong(it))
    //                ContactRiskWarningDisposition newContactRiskWarningDisposition = new ContactRiskWarningDisposition()
    //                newContactRiskWarningDisposition.type = contactRiskWarningDisposition.type
    //                newContactRiskWarningDisposition.description = contactRiskWarningDisposition.description
    //                newContactRiskWarningDisposition.status = contactRiskWarningDisposition.status
    //                newContactRiskWarningDisposition.endDate = contactRiskWarningDisposition.endDate
    //                newContactRiskWarningDisposition.startDate = contactRiskWarningDisposition.startDate
    //                newContactRiskWarningDisposition.createBy = contactRiskWarningDisposition.createBy
    //                newContactRiskWarningDisposition.createdDate = contactRiskWarningDisposition.createdDate
    //                newContactRiskWarningDisposition.contact = contact
    //                if (newContactRiskWarningDisposition.validate())
    //                {
    //                    newContactRiskWarningDisposition?.save()
    //                }
    //                else
    //                {
    //                    println newContactRiskWarningDisposition?.errors
    //                }
    //            }
    //        }
    //        redirect url: targetUri
    //    }

    // 押品有效到期监测
    def effectiveMaturityWarning(Integer max)
    {
        params.max = Math.min(max ?: 10, 100)
        params.offset = params.offset ? params.offset.toInteger() : 0
        def externalId = params['externalId']
        def name = params['name']
        def type = params['type']
        def expires = params['expires']
        def status = params['status']
        def communityId = params['communityId']
        //        def sql = "from RiskWarning r where r.type.code = '14' and r.isWarning = '1' "
        //        if (externalId)
        //        {
        //            sql += " and r.collateral.externalId like '%${externalId}%' "
        //        }
        //        if (name)
        //        {
        //            sql += " and r.collateral.name like '%${name}%' "
        //        }
        //        if (type)
        //        {
        //            sql += " and r.collateral.type.id = ${type}"
        //        }
        //        if (status)
        //        {
        //            sql += " and r.status.id = '${status}' "
        //        }
        //        if (expires)
        //        {
        //            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd")
        //            def currentDateStr = sdf.format(new Date())
        //            if (expires == "true")
        //            {
        //                sql += " and r.collateral.estate.endDate < '${currentDateStr}'"
        //            }
        //            if (expires == "false")
        //            {
        //                sql += " and r.collateral.estate.endDate >= '${currentDateStr}'"
        //            }
        //        }
        //        if(communityId){
        //            sql += " and r.collateral.estate.communityId = ${communityId} "
        //        }
        //        def sql1 = " select count(*) " + sql
        //        sql += " order by r.modifiedDate desc "
        //        def riskWarningList = RiskWarning.executeQuery(sql, [max: params.max, offset: params.offset]).asList()
        //        def riskWarningCount = RiskWarning.executeQuery(sql1)
        //        respond riskWarningList, model: [riskWarningList: riskWarningList, riskWarningCount: riskWarningCount[0]]
    }

    //    押品有效到期监测详情页
    def effectiveMaturityWarningShow(House collateral)
    {
        def estate = null
        //        if(!collateral){
        //            estate = Estate.findById(Long.parseLong(params["id"]))
        //            collateral = Collateral.findByEstate(estate)
        //            params.status = RiskWarning.findByCollateral(collateral)?.status?.name
        //        }else{
        //            estate = collateral?.estate
        //        }
        //        println "params:   "+params
        //
        //        def zoneNumber = estate?.city?.zoneNumber
        //        def communityId = estate.communityId
        //        //小区详情
        //        def community = apiService.community(zoneNumber, communityId)
        //        //小区照片
        //        def communityPicArr = apiService.picture(zoneNumber, communityId, 5, 3)
        //        //成交案例列表
        //        def saleList = apiService.sale(zoneNumber, communityId)
        //        //挂牌案例列表
        //        def listings = apiService.listing(zoneNumber, communityId)
        //        // 贷款信息
        //        def mortgageList = MortgageCollateral.findAllByCollateral(collateral)*.mortgage
        //
        //        def replaceCollateral = collateral?.replacementCollateral

        respond collateral, model: [params: params]
    }

    /**
     * 集中度风险*/
    def concentrationWarning(Integer max)
    {
        params.max = Math.min(max ?: 10, 100)
        params.offset = params.offset ? params.offset.toInteger() : 0
        def address = params['address']
        def communityName = params['communityName']
        def status = params['status']
        def sql = "from RiskWarning r where r.type.code = '7' and r.isWarning = '1' "
        if (address)
        {
            sql += " and r.community.address like '%${address}%' "
        }
        if (communityName)
        {
            sql += " and r.community.communityName like '%${communityName}%' "
        }
        if (status)
        {
            sql += " and r.status.id = '${status}' "
        }
        def sql1 = " select count(*) " + sql
        sql += " order by r.modifiedDate desc "

        def riskWarningList = RiskWarning.executeQuery(sql, [max: params.max, offset: params.offset]).asList()
        def riskWarningCount = RiskWarning.executeQuery(sql1)
        respond riskWarningList, model: [riskWarningList: riskWarningList, riskWarningCount: riskWarningCount[0]]
    }

    //    集中度预警押品详情页
    def concentrationWarningShow(Community community)
    {
        if (!community)
        {
            def communityId = Long.parseLong(params['id'])
            //            community = Community.findByCommunityId(communityId)
        }
        respond community
    }

    //押品覆盖率预警
    def collateralCoverageRateWarning(Integer max)
    {
        params.max = Math.min(max ?: 10, 100)
        params.offset = params.offset ? params.offset.toInteger() : 0
        def address = params['address']
        def communityName = params['communityName']
        def status = params['status']
        def sql = "from RiskWarning r where r.type.code = '10' and r.isWarning = '1' "
        if (address)
        {
            sql += " and r.community.address like '%${address}%' "
        }
        if (communityName)
        {
            sql += " and r.community.communityName like '%${communityName}%' "
        }
        if (status)
        {
            sql += " and r.status.id = '${status}' "
        }
        def sql1 = " select count(*) " + sql
        sql += " order by r.modifiedDate desc "

        def riskWarningList = RiskWarning.executeQuery(sql, [max: params.max, offset: params.offset]).asList()
        def riskWarningCount = RiskWarning.executeQuery(sql1)
        respond riskWarningList, model: [riskWarningList: riskWarningList, riskWarningCount: riskWarningCount[0]]
    }

    //    押品覆盖率预警详情页
    def collateralCoverageRateWarningShow(Community community)
    {
        if (!community)
        {
            def communityId = Long.parseLong(params['id'])
            //            community = Community.findByCommunityId(communityId)
        }
        respond community
    }

    //手机号停用预警
    def cellphoneStopWarning()
    {

    }

    //手机号停用预警详情
    def cellphoneStopWarningShow()
    {

    }

    //工作地点频繁预警
    def frequentlyWorkplaceWarning()
    {

    }

    //工作地点频繁预警详情
    def frequentlyWorkplaceWarningShow()
    {

    }

    // 押品效期预警（组件内容）
    // def effectiveMaturityInit()
    // {
    //     println "======================== effectiveMaturityInit  ============================"
    //     def count = 0
    //     def user = User.findById(springSecurityService.principal.id)
    //     def sql = "select new map(c.id as id, e.endDate as endDate) from Collateral c left join c.estate e where date_part('day', e.endDate - CURRENT_DATE) <= 1 and date_part('day', e.endDate - CURRENT_DATE) >= 0 and c.account.id in " + Account.FilterAccountSql(user)
    //     def result = Collateral.executeQuery(sql).asList()
    //     result?.each
    //     {
    //         def collateral = Collateral.findById(it?.id)
    //         def type = RiskWarningTypeDict.findByCode("14")
    //         def status = RiskWarningStatusDict.findByCode("2")
    //         def riskWarning = RiskWarning.findByCollateralAndType(collateral, type)
    //         if (!riskWarning)
    //         {
    //             riskWarning = new RiskWarning()
    //         }

    //         riskWarning.type = type
    //         riskWarning.collateral = collateral
    //         riskWarning.status = status
    //         if (riskWarning.validate())
    //         {
    //             riskWarning.save flush: true
    //             count++
    //         }
    //         else
    //         {
    //             println riskWarning.errors
    //         }
    //         println "warning counts: " + count
    //     }
    //     println "finish: " + count
    //     redirect action: 'effectiveMaturityWarning'
    // }

    // 小区评分预警（组件内容）
    // def buildingScoreInit()
    // {
    //     println "======================== buildingScoreInit  ============================"
    //     def count = 0
    //     def result = Community.findAllByCommunityScoreLessThan(3)
    //     result?.each
    //     {
    //         def type = RiskWarningTypeDict.findByCode("15")
    //         def status = RiskWarningStatusDict.findByCode("2")
    //         def riskWarning = RiskWarning.findByCommunityAndType(it, type)
    //         if (!riskWarning)
    //         {
    //             riskWarning = new RiskWarning()
    //         }

    //         riskWarning.type = type
    //         riskWarning.community = it
    //         riskWarning.status = status
    //         if (riskWarning.validate())
    //         {
    //             riskWarning.save flush: true
    //             count++
    //         }
    //         else
    //         {
    //             println riskWarning.errors
    //         }
    //         println "warning counts: " + count
    //     }

    //     println "finish: " + count

    //     redirect action: 'buildingScoreWarning'
    // }

    //    押品覆盖率（组件内容）
    // def collateralCoverageRateInit()
    // {
    //     println "======================== collateralCoverageRateInit  ============================"

    //     def warningCounts = 0
    //     def communityCounts = 0
    //     def user = User.findById(springSecurityService.principal.id)
    //     def db = new groovy.sql.Sql(dataSource)
    //     def sql = "select community_id as id, count(*) as estatecounts, (select community.total_house_hold_count from community where community.community_id = estate.community_id) as housecounts from estate where community_id is not null and account_id in " + Account.FilterAccountSql(user) + " GROUP BY community_id"
    //     def result = db.rows(sql).asList()
    //     result?.each
    //     {
    //         def community = Community.findByCommunityId(it?.id)
    //         def estateCounts = it?.estatecounts
    //         def housecounts = it?.housecounts
    //         def communityCoverage = 0
    //         try
    //         {
    //             if (estateCounts && estateCounts != 0 && housecounts && housecounts != 0)
    //             {
    //                 communityCoverage = estateCounts / housecounts
    //             }

    //             if (!community?.communityCoverage)
    //             {
    //                 community?.communityCoverage = communityCoverage
    //                 community.save(flush: true)
    //                 communityCounts++
    //                 println communityCounts
    //                 if (communityCoverage >= 0.1)
    //                 {
    //                     def type = RiskWarningTypeDict.findByCode("10")
    //                     def status = RiskWarningStatusDict.findByCode("2")
    //                     def riskWarning = RiskWarning.findByCommunityAndType(community, type)
    //                     if (!riskWarning)
    //                     {
    //                         riskWarning = new RiskWarning()
    //                     }

    //                     riskWarning.type = type
    //                     riskWarning.community = community
    //                     riskWarning.status = status
    //                     riskWarning.save(flush: true)
    //                     warningCounts++
    //                     println "warningCounts:" + warningCounts
    //                 }
    //             }
    //         }
    //         catch(Exception e)
    //         {
    //             println e.printStackTrace()
    //         }
    //         db.commit()
    //     }

    //     println "finish: " + communityCounts
    //     println "finish: " + warningCounts

    //     redirect action: 'collateralCoverageRateWarning'
    // }

    /**
     * 预警处置*/
    def riskWarningDeal()
    {
        def status = ""
        def riskWarningId = params['id']
        def riskWarning = RiskWarning.findById(riskWarningId)
        try
        {
            //            riskWarning.status = RiskWarningStatusDict.findByCode('3')
            //            riskWarning.save flush: true
            //            status = "success"
        }
        catch (Exception e)
        {
            status = "false"
            e.printStackTrace()
        }
        render([status: status] as JSON)
    }

    /**
     * 预警删除*/
    def riskWarningDelete()
    {
        def status = ""
        def riskWarningId = params['id']
        def riskWarning = RiskWarning.findById(riskWarningId)
        try
        {
            riskWarning.isWarning = false
            riskWarning.save flush: true
            status = "success"
        }
        catch (Exception e)
        {
            status = "false"
            e.printStackTrace()
        }
        render([status: status] as JSON)
    }

    //    // 组建执行
    //    def excuteComponent()
    //    {
    //        def componentCode = params['componentCode']
    //        def component = Component.findByCode(componentCode)
    //        def view = componentService.evaluate component
    //        redirect action: view
    //    }
    //
    //    // 带service参数组件执行
    //    def excuteComponentWithParam()
    //    {
    //        def serviceParams = [springSecurityService: springSecurityService, apiService: apiService, dataSource: dataSource, scoreApiService: scoreApiService, riskWarningService: riskWarningService]
    //        def componentCode = params['componentCode']
    //        def component = Component.findByCode(componentCode)
    //
    //        def view = componentService.evaluate(component, serviceParams)
    //        redirect action: view
    //    }

    //贷款预警列表
    def mortgageWarning()
    {

    }

    //    //贷款预警详情
    //    def mortgageWarningShow(Mortgage mortgage){
    //        mortgage = Mortgage.findById(515717)
    //
    //        respond mortgage
    //    }

    // 预警处置页面
    def contactOverdueWarningEdit(RiskWarning riskWarning)
    {
        params['targetUri'] = request.getHeader('referer')
        respond riskWarning, model: [params: params]
    }

    def contactOverdueWarningEdit1(RiskWarning riskWarning)
    {
        params['targetUri'] = request.getHeader('referer')
        respond riskWarning, model: [params: params]
    }

    // def mortgageWarningDisposalSave(RiskWarning riskWarning)
    // {
    //     if (riskWarning.validate())
    //     {
    //         riskWarning.save flush: true
    //     }
    //     else
    //     {
    //         println riskWarning.errors
    //     }
    //     def serviceParams = [springSecurityService: springSecurityService, riskWarning: riskWarning, riskWarningService: riskWarningService]
    //     def component = Component.findByCode("initRiskWarningDisposalFlow")

    //     componentService.evaluate(component, serviceParams)

    //     def user = User.findById(springSecurityService.principal.id)
    //     def flowStage = RiskWarningFlowStage.findByRiskWarningAndStage(riskWarning, riskWarning?.stage)
    //     def roleSql = ""
    //     def roleList = UserRole.findAllByUser(user)*.role
    //     if (roleList)
    //     {
    //         String roleIdList = roleList*.id?.toString()
    //         roleSql += " and role.id in (" + roleIdList?.substring(1, roleIdList.lastIndexOf("]")) + ")"
    //     }

    //     def approveRoleFlag = RiskWarningFlowStageRole.find("from RiskWarningFlowStageRole where flowStage.id = ? and teamRole.id = ? " + roleSql, [flowStage?.id, TeamRole.APPROVAL()?.id]) && true
    //     if(!approveRoleFlag)
    //     {
    //         flash.message = "权限校验失败"
    //         redirect action:'contactOverdueWarning'
    //         return
    //     }

    //     def comment = new Comment()
    //     comment.riskWarning = riskWarning
    //     comment.warningStage = riskWarning?.stage
    //     comment.comment = params['comment']
    //     comment.save()

    //     def map = riskWarningService.approve(riskWarning)
    //     if(!map['flag'])
    //     {
    //         flash.message = map['message']
    //         redirect action:'contactOverdueWarning'
    //         return
    //     }

    //     redirect action: 'contactOverdueWarning'
    // }

    def mortgageWarningDisposalSave1()
    {
        def riskWarning = RiskWarning.findById(params['riskWarning'])
        def department = Department.findById(params['department'])
        riskWarning.disposalDepartment = department
        if (riskWarning.validate())
        {
            riskWarning.save flush: true
        }
        else
        {
            println riskWarning.errors
        }

        // def user = User.findById(springSecurityService.principal.id)
        // def flowStage = RiskWarningFlowStage.findByRiskWarningAndStage(riskWarning, riskWarning?.stage)
        // def roleSql = ""
        // def roleList = UserRole.findAllByUser(user)*.role
        // if (roleList)
        // {
        //     String roleIdList = roleList*.id?.toString()
        //     roleSql += " and role.id in (" + roleIdList?.substring(1, roleIdList.lastIndexOf("]")) + ")"
        // }

        // def approveRoleFlag = RiskWarningFlowStageRole.find("from RiskWarningFlowStageRole where flowStage.id = ? and teamRole.id = ? " + roleSql, [flowStage?.id, TeamRole.APPROVAL()?.id]) && true
        // if(!approveRoleFlag)
        // {
        //     flash.message = "权限校验失败"
        //     redirect action:'overdueCollectionIndex'
        //     return
        // }

        // def map = riskWarningService.approve(riskWarning)
        // if(!map['flag'])
        // {
        //     flash.message = map['message']
        //     redirect action:'overdueCollectionIndex'
        //     return
        // }

        redirect url: request.getHeader('referer')
    }

    def mortgageWarningDisposalAsign(RiskWarning riskWarning)
    {
        params['targetUri'] = request.getHeader("referer")
        respond riskWarning
    }

    def mortgageWarningDisposalAsignSave(RiskWarning riskWarning)
    {
        if (riskWarning.validate())
        {
            riskWarning.save flush: true
        }
        else
        {
            println riskWarning.errors
        }

        redirect url: params['targetUri']
    }

    // 登记流程推进
    def approve(RiskWarning riskWarning)
    {
        def user = User.findById(springSecurityService.principal.id)

        redirect action: 'contactOverdueWarningIndex'
    }

    def reject(RiskWarning riskWarning)
    {
        def user = User.findById(springSecurityService.principal.id)
        def approveRoleFlag
        if (!approveRoleFlag)
        {
            flash.message = "权限校验失败"
            redirect url: request.getHeader("referer")
            return
        }

        def canReject = riskWarningService.reject(riskWarning)
        if (canReject)
        {
            redirect action: params['targetUri']
        }
        else
        {
            flash.message = "对不起，无权限拒绝"
            redirect url: request.getHeader("referer")
            return
        }
    }

    def initWarningFlow(RiskWarning riskWarning)
    {
        def workFlow = riskWarning?.workflow
        if (!workFlow)
        {
            flash.message = "请先选择工作流"
            redirect url: request.getHeader("referer")
            return
        }
        riskWarningService.initRiskWarningFlowStage(riskWarning, workFlow)

        redirect url: request.getHeader("referer")
    }

    def riskWarningAnalyze()
    {

    }

    def riskWarningCollateral()
    {
        respond new RiskWarning(), model: [list: RiskWarning.list(max: 12)]
    }

    def riskWarningMortgage()
    {
        respond new RiskWarning(), model: [list: RiskWarning.list(max: 12)]
    }

    def riskWarningCommunity()
    {
        respond new RiskWarning(), model: [list: RiskWarning.list(max: 12)]
    }

    def riskWarningContact()
    {
        respond new RiskWarning(), model: [list: RiskWarning.list(max: 12)]
    }

    def riskWarningAccount()
    {
        def max = params.max ? params.max.toInteger() : 10
        def offset = params.offset ? params.offset.toInteger() : 0
        def name = params["name"]
        def city = params["city"]
        def warningType = params["warningType"]
        def district = params["district"]
        def operatingState = params["operatingState"]
        def fullName = params["fullName"]
        def workflowStatus = params["workflowStatus"]
        def user = User.findById(springSecurityService.principal.id)

        respond null
    }

    def riskWarningAccountShow(RiskWarning riskWarning)
    {

        respond riskWarning
    }

    // 机构预警处置页面
    def riskWarningAccountEdit(RiskWarning riskWarning)
    {
        params['targetUri'] = request.getHeader('referer')
        respond riskWarning, model: [params: params]
    }

    // 登记流程推进
    def approve1(RiskWarning riskWarning)
    {
        redirect action: 'riskWarningAccount'
    }

}
